package com.school.sports.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.school.sports.entity.SysDictData;
import com.school.sports.mapper.SysDictDataMapper;
import com.school.sports.service.SysDictDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 字典数据服务实现类
 */
@Slf4j
@Service
public class SysDictDataServiceImpl extends ServiceImpl<SysDictDataMapper, SysDictData> implements SysDictDataService {

    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    @Override
    public IPage<SysDictData> getDictDataPage(Integer currentPage, Integer pageSize, SysDictData sysDictData) {
        // 创建分页对象
        Page<SysDictData> page = new Page<>(currentPage, pageSize);

        // 构建查询条件
        QueryWrapper<SysDictData> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);

        if (sysDictData.getDictTypeId() != null) {
            queryWrapper.eq("dict_type_id", sysDictData.getDictTypeId());
        }
        if (StringUtils.hasText(sysDictData.getDictLabel())) {
            queryWrapper.like("dict_label", sysDictData.getDictLabel());
        }
        if (StringUtils.hasText(sysDictData.getDictValue())) {
            queryWrapper.like("dict_value", sysDictData.getDictValue());
        }
        if (sysDictData.getStatus() != null) {
            queryWrapper.eq("status", sysDictData.getStatus());
        }

        // 按字典类型ID、排序、创建时间排序
        queryWrapper.orderByAsc("dict_type_id", "dict_sort", "created_at");

        return this.page(page, queryWrapper);
    }

    @Override
    public List<SysDictData> getDictDataByTypeId(Long dictTypeId) {
        return sysDictDataMapper.selectByDictTypeId(dictTypeId);
    }

    @Override
    public List<SysDictData> getDictDataByTypeCode(String dictTypeCode) {
        return sysDictDataMapper.selectByDictTypeCode(dictTypeCode);
    }

    @Override
    public SysDictData getDictDataByTypeCodeAndValue(String dictTypeCode, String dictValue) {
        return sysDictDataMapper.selectByDictTypeCodeAndValue(dictTypeCode, dictValue);
    }

    @Override
    public SysDictData getDictDataByTypeCodeAndLabel(String dictTypeCode, String dictLabel) {
        return sysDictDataMapper.selectByDictTypeCodeAndLabel(dictTypeCode, dictLabel);
    }

    @Override
    public boolean addDictData(SysDictData sysDictData, Long currentUserId) {
        // 检查字典值是否已存在
        if (checkDictValueExists(sysDictData.getDictTypeId(), sysDictData.getDictValue(), null)) {
            log.warn("字典值已存在：{}", sysDictData.getDictValue());
            return false;
        }

        // 设置默认值
        sysDictData.setCreatedAt(LocalDateTime.now());
        sysDictData.setUpdatedAt(LocalDateTime.now());
        sysDictData.setCreatedBy(currentUserId);
        sysDictData.setUpdatedBy(currentUserId);
        sysDictData.setDeleted(0);

        if (sysDictData.getStatus() == null) {
            sysDictData.setStatus(1); // 默认启用
        }
        if (sysDictData.getIsDefault() == null) {
            sysDictData.setIsDefault(0); // 默认非默认值
        }
        if (sysDictData.getDictSort() == null) {
            sysDictData.setDictSort(0); // 默认排序为0
        }

        return this.save(sysDictData);
    }

    @Override
    public boolean updateDictData(SysDictData sysDictData, Long currentUserId) {
        // 检查字典数据是否存在
        SysDictData existingDictData = this.getById(sysDictData.getId());
        if (existingDictData == null) {
            log.warn("字典数据不存在：{}", sysDictData.getId());
            return false;
        }

        // 检查字典值是否已存在（排除当前字典数据）
        if (checkDictValueExists(sysDictData.getDictTypeId(), sysDictData.getDictValue(), sysDictData.getId())) {
            log.warn("字典值已存在：{}", sysDictData.getDictValue());
            return false;
        }

        // 如果设置为默认值，需要将同类型的其他默认值取消
        if (sysDictData.getIsDefault() != null && sysDictData.getIsDefault() == 1) {
            clearOtherDefaultValues(sysDictData.getDictTypeId(), sysDictData.getId());
        }

        // 设置更新信息
        sysDictData.setUpdatedAt(LocalDateTime.now());
        sysDictData.setUpdatedBy(currentUserId);

        return this.updateById(sysDictData);
    }

    @Override
    public boolean deleteDictData(Long dictDataId) {
        // 逻辑删除
        SysDictData dictData = new SysDictData();
        dictData.setId(dictDataId);
        dictData.setDeleted(1);
        dictData.setUpdatedAt(LocalDateTime.now());
        return this.updateById(dictData);
    }

    @Override
    @Transactional
    public boolean batchDeleteDictData(List<Long> dictDataIds) {
        // 批量逻辑删除
        LocalDateTime now = LocalDateTime.now();
        List<SysDictData> updateDictData = dictDataIds.stream()
                .map(dictDataId -> {
                    SysDictData dictData = new SysDictData();
                    dictData.setId(dictDataId);
                    dictData.setDeleted(1);
                    dictData.setUpdatedAt(now);
                    return dictData;
                })
                .collect(Collectors.toList());

        return this.updateBatchById(updateDictData);
    }

    @Override
    public boolean updateDictDataStatus(Long dictDataId, Integer status, Long currentUserId) {
        SysDictData dictData = new SysDictData();
        dictData.setId(dictDataId);
        dictData.setStatus(status);
        dictData.setUpdatedAt(LocalDateTime.now());
        dictData.setUpdatedBy(currentUserId);

        return this.updateById(dictData);
    }

    @Override
    public boolean checkDictValueExists(Long dictTypeId, String dictValue, Long excludeId) {
        return sysDictDataMapper.countByDictTypeIdAndValue(dictTypeId, dictValue, excludeId) > 0;
    }

    @Override
    public Map<String, List<SysDictData>> getAllEnabledDictData() {
        List<SysDictData> dictDataList = sysDictDataMapper.selectAllEnabledDictData();

        return dictDataList.stream()
                .collect(Collectors.groupingBy(
                        SysDictData::getDictTypeCode
                ));
    }

    @Override
    public List<SysDictData> getDictDataByLabel(String dictLabel) {
        return sysDictDataMapper.selectByDictLabelLike(dictLabel);
    }

    @Override
    public boolean refreshDictDataCache() {
        try {
            // 获取所有启用的字典数据
            List<SysDictData> dictDataList = sysDictDataMapper.selectAllEnabledDictData();

            // 这里可以添加缓存刷新逻辑，例如更新Redis缓存
            log.info("刷新字典数据缓存，共{}条数据", dictDataList.size());

            return true;
        } catch (Exception e) {
            log.error("刷新字典数据缓存失败", e);
            return false;
        }
    }

    @Override
    @Transactional
    public boolean batchUpdateDictSort(Map<Long, Integer> dictDataMap, Long currentUserId) {
        try {
            LocalDateTime now = LocalDateTime.now();

            for (Map.Entry<Long, Integer> entry : dictDataMap.entrySet()) {
                Long dictDataId = entry.getKey();
                Integer dictSort = entry.getValue();

                SysDictData dictData = new SysDictData();
                dictData.setId(dictDataId);
                dictData.setDictSort(dictSort);
                dictData.setUpdatedAt(now);
                dictData.setUpdatedBy(currentUserId);

                this.updateById(dictData);
            }

            return true;
        } catch (Exception e) {
            log.error("批量更新字典数据排序失败", e);
            return false;
        }
    }

    /**
     * 清除同类型的其他默认值
     * @param dictTypeId 字典类型ID
     * @param excludeId 排除的ID
     */
    private void clearOtherDefaultValues(Long dictTypeId, Long excludeId) {
        QueryWrapper<SysDictData> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_type_id", dictTypeId);
        queryWrapper.eq("is_default", 1);
        queryWrapper.eq("deleted", 0);
        if (excludeId != null) {
            queryWrapper.ne("id", excludeId);
        }

        List<SysDictData> defaultDictDataList = this.list(queryWrapper);

        if (!defaultDictDataList.isEmpty()) {
            LocalDateTime now = LocalDateTime.now();
            List<SysDictData> updateList = defaultDictDataList.stream()
                    .map(dictData -> {
                        dictData.setIsDefault(0);
                        dictData.setUpdatedAt(now);
                        return dictData;
                    })
                    .collect(Collectors.toList());

            this.updateBatchById(updateList);
        }
    }
}